//
//  M1CLLocationManage.m
//  NewMarryU
//
//  Created by Cedar on 2018/7/23.
//  Copyright © 2018年 Cedar. All rights reserved.
//

#import "M1CLLocationManage.h"
#import "M1LocationTransform.h"
@interface M1CLLocationManage ()
@property (nonatomic,copy)SuccessBlock m1_successBlock;
@property (nonatomic,copy)FaildBlock   m1_faildBlock;

@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, assign) CLLocationCoordinate2D coord;
@end

@implementation M1CLLocationManage

+(instancetype)shareInstance{
    static dispatch_once_t once;
    static M1CLLocationManage *shared=nil;
    dispatch_once(&once, ^{
        shared=[[M1CLLocationManage alloc]init];
    });
    return shared;
}


-(void)m1_getLocation:(SuccessBlock)successBlock faild:(FaildBlock)faildBlock{
    self.m1_successBlock=successBlock;
    self.m1_faildBlock=faildBlock;
    if (![CLLocationManager locationServicesEnabled]) {
        self.m1_faildBlock(@"定位服务不可用");
        self.m1_faildBlock=nil;
        return;
    }
    
    if (!_locationManager) {
        _locationManager=[[CLLocationManager alloc]init];
    }
    
    _locationManager.delegate=self;
    
    [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8) {
        [_locationManager requestWhenInUseAuthorization];//只在前台开启定位
    }
    [_locationManager startUpdatingLocation];
}

#pragma mark CLLocationManagerDelegate Methods

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    CLGeocoder *geoCoder=[[CLGeocoder alloc]init];
    NSMutableArray
    *userDefaultLanguages = [[NSUserDefaults standardUserDefaults]
                             objectForKey:@"AppleLanguages"];
    

    CLLocation *currentLocation = [locations lastObject];
    CLLocationCoordinate2D coor = currentLocation.coordinate;
    coor = [M1LocationTransform m1_locationTransform:coor];
    [M1SaveTool m1_saveLocation:@{@"lat":[NSString stringWithFormat:@"%.6f",coor.latitude],
                                  @"lon":[NSString stringWithFormat:@"%.6f",coor.longitude]
                                  }];
    [[NSUserDefaults
      standardUserDefaults] setObject:[NSArray arrayWithObjects:@"zh-hans",
                                       nil] forKey:@"AppleLanguages"];
    
    [geoCoder reverseGeocodeLocation:locations[0] completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        NSString *m1_city;
        NSString *m1_pro;
        for (CLPlacemark * placemark in placemarks) {
            
            m1_city = [placemark locality];
            m1_pro=[placemark administrativeArea];
            if(!m1_city){
                m1_city=[placemark administrativeArea];
            }
            
            if (!m1_pro) {
                m1_pro = m1_city;
                m1_city = [placemark subLocality];
            }
        }
        
        if (m1_city&&m1_city.length>0) {
            m1_pro =  [m1_pro stringByReplacingOccurrencesOfString:@"省" withString:@""];
            m1_pro =  [m1_pro stringByReplacingOccurrencesOfString:@"市" withString:@""];
            m1_pro =  [m1_pro stringByReplacingOccurrencesOfString:@"回族自治区" withString:@""];
            m1_pro =  [m1_pro stringByReplacingOccurrencesOfString:@"壮族自治区" withString:@""];
            m1_pro =  [m1_pro stringByReplacingOccurrencesOfString:@"维吾尔自治区" withString:@""];
            m1_pro =  [m1_pro stringByReplacingOccurrencesOfString:@"行政自治区" withString:@""];
            m1_pro =  [m1_pro stringByReplacingOccurrencesOfString:@"自治区" withString:@""];
            
            
            m1_city =  [m1_city stringByReplacingOccurrencesOfString:@"省" withString:@""];
            m1_city =  [m1_city stringByReplacingOccurrencesOfString:@"市" withString:@""];
            m1_city =  [m1_city stringByReplacingOccurrencesOfString:@"地区" withString:@""];
            m1_city =  [m1_city stringByReplacingOccurrencesOfString:@"藏族自治州" withString:@""];
            
            
            if (self.m1_successBlock) {
                self.m1_successBlock(m1_pro,m1_city);
                self.m1_successBlock=nil;
                NSDictionary *m1_location = @{@"lat":[NSString stringWithFormat:@"%.6f",coor.latitude],
                                              @"lon":[NSString stringWithFormat:@"%.6f",coor.longitude],
                                              @"city":[NSString stringWithFormat:@"%@-%@",m1_pro,m1_city]
                                              };
                [M1SaveTool m1_saveLocation:m1_location];
            }
        }else{
            if (self.m1_faildBlock) {
                self.m1_faildBlock(@"定位失败");
                self.m1_faildBlock=nil;
            }
        }
        [[NSUserDefaults
          standardUserDefaults] setObject:userDefaultLanguages
         forKey:@"AppleLanguages"];
    }];
    
    [_locationManager stopUpdatingLocation];
}

//定位失败
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    [_locationManager stopUpdatingLocation];
    if ([error code]==kCLErrorDenied) {
        if (self.m1_faildBlock) {
            self.m1_faildBlock(@"被拒绝访问定位");
            self.m1_faildBlock=nil;
        }
        
    }
    else if ([error code]==kCLErrorLocationUnknown) {
        if (self.m1_faildBlock) {
            self.m1_faildBlock(@"无法获取位置信息");
            self.m1_faildBlock=nil;
        }
    }
    else{
        if (self.m1_faildBlock) {
            self.m1_faildBlock(@"定位失败");
            self.m1_faildBlock=nil;
        }
    }
    
}
@end
